<script setup name="Admin">
	import {ref, reactive} from 'vue'
	import {adminApi} from '@/api/admin/admin.js'
	import {
		Plus,
		Delete,
		Edit,
		Message,
		Search,
		Close,
	} from '@element-plus/icons-vue'
	import {ElMessage, ElMessageBox} from "element-plus";
	
	//获取当前登录admin的role类型
	const adminInfoStore = useAdminInfoStore();
	const loginAdmin = adminInfoStore.admin.role
	
	//表格数据
	let adminList = ref([])
	const total = ref(0)
	
	//分页信息，搜索条件
	const adminQuery = reactive({
		page: 1,
		limit: 10,
		name: '',
		phone: ''
	})
	
	//加载数据
	const loadData = () => {
		adminApi.list(adminQuery).then(result => {
			adminList.value = result.data.list
			total.value = result.data.total
		})
	}
	loadData()
	
	//搜索
	const onSearch = () => {
		adminQuery.page = 1
		loadData()
	}
	
	//重置搜索条件
	const originData = () => ({name: "", phone: "", beginUpdateTime: "", endUpdateTime: ""});
	const resetForm = () => {
		Object.assign(adminQuery, originData());
		loadData();
	};
	
	//单个删除
	const deleteById = (id) => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			.then(() => {
				adminApi.deleteById(id).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
				
			})
	}
	
	//批量删除
	const ids = ref([])
	const handleSelectionChange = (rows) => {
		//获取选中的id数组
		ids.value = rows.map(row => row.id)
	}
	const deleteAll = () => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			//点击确认删除
			.then(() => {
				ids.value = ids.value.join(',')
				adminApi.deleteAll(ids.value).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success'})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//添加
	const dialogVisible = ref(false)  //添加&编辑弹出框默认关闭
	const admin = ref({})   //添加/编辑/查看详情的管理员信息
	const title = ref()   //添加/编辑的标题
	const showAddDialog = () => {
		dialogVisible.value = true   //打开弹窗
		title.value = '添加'
		admin.value = {}   //将管理员信息清除
	}
	const add = () => {   //点击确定
		adminApi.add(admin.value).then(result => {
			if (result.code === 0) {
				ElMessage({message: result.msg, type: 'success'})
				dialogVisible.value = false
			} else {
				ElMessage.error(result.msg)
			}
			//刷新表格
			loadData()
		})
	}
	import {useTokenStore} from '@/store/token.js'
	import {useAdminInfoStore} from "@/store/adminInfo.js";//上传头像图片
	const tokenStore = useTokenStore();
	const headers = ref({
		//携带token传递到后端
		Authorization: tokenStore.token
	});
	const handleAvatarSuccess = (result) => {
		admin.value.image = result.data
	}
	
	//超级管理员操作修改账号角色类型
	const updateRole = (row) => {
		adminApi.updateRole(row.id, row.role).then(result => {
			if (result.code === 0) {
				ElMessage.success(result.msg)
			} else {
				ElMessage.error(result.msg)
			}
		})
	}
	
	//超级管理员操作修改账号status状态
	const updateSatus = (row) => {
		adminApi.updateStatus(row.id, row.status).then(result => {
			if (result.code === 0) {
				ElMessage.success(result.msg)
			} else {
				ElMessage.error(result.msg)
			}
		})
	}
	
	//查看管理员信息详情
	const dialogDetailsVisible = ref(false)
	const handleClick = (id) => {
		adminApi.selectById(id).then(result => {
			dialogDetailsVisible.value = true
			admin.value = result.data
		})
	}
	
	//超级管理员重置密码
	const defaultPassword = (id) => {
		ElMessageBox.confirm(
			'确认重置为默认密码吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			//点击确认重置
			.then(() => {
				adminApi.defaultPassword(id).then(result => {
					if (result.code === 0) {
						ElMessage.success(result.msg)
					} else {
						ElMessage.error(result.msg)
					}
				})
			})
	}
</script>

<template>
	<div class="back">
		<el-card class="">
			<template #header>
				<div class="header">
					<el-button type="success" :icon="Plus" @click="showAddDialog">添加</el-button>
					<el-button type="danger" :icon="Delete" v-if="loginAdmin==1" @click="deleteAll">批量删除</el-button>
				</div>
			</template>
			<!--		搜索框-->
			<el-form :inline="true" :model="formInline" class="demo-form-inline">
				<el-form-item label="名字">
					<el-input v-model="adminQuery.name" placeholder="请输入姓名" clearable style="width: 140px;"/>
				</el-form-item>
				<el-form-item label="手机号">
					<el-input v-model="adminQuery.phone" placeholder="请输入手机号" clearable style="width: 140px;"/>
				</el-form-item>
				<el-form-item label="更新时间">
					<el-date-picker
						v-model="adminQuery.beginUpdateTime"
						type="datetime"
						value-format="YYYY-MM-DD HH:mm:ss"
						placeholder="开始时间"
						style="width: 190px;"
					/>
					-
					<el-date-picker
						v-model="adminQuery.endUpdateTime"
						type="datetime"
						value-format="YYYY-MM-DD HH:mm:ss"
						placeholder="结束时间"
						style="width: 190px;"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
					<el-button @click="resetForm" round>重置</el-button>
				</el-form-item>
			</el-form>
			
			<!--		信息表格-->
			<el-table ref="multipleTableRef" :data="adminList" border stripe style="width: 100%"
					  @selection-change="handleSelectionChange" height="450px">
				<el-table-column type="selection" :selectable="selectable" width="40"/>
				<el-table-column fixed prop="id" label="ID" sortable width="70" align="center"/>
				<el-table-column prop="name" label="姓名" align="center" width="120"/>
				<el-table-column prop="nickName" label="昵称" align="center" width="90"/>
				<el-table-column prop="email" label="邮箱" align="center" width="200"/>
				<el-table-column prop="phone" label="联系方式" align="center" width="130"/>
				<el-table-column prop="image" label="头像" align="center" width="150" show-overflow-tooltip>
					<template #default="scope">
						<img :src="scope.row.image" style="max-height: 40px;max-width: 120px"/>
					</template>
				</el-table-column>
				<el-table-column prop="role" label="角色类型" align="center" width="150">
					<template #default="scope">
						<div v-if="loginAdmin == 2 && scope.row.role==1">超级管理员</div>
						<div v-if="loginAdmin == 2 && scope.row.role==2">普通管理员</div>
						<el-switch
							v-model="scope.row.role"
							v-if="loginAdmin==1"
							class="ml-2"
							inline-prompt
							size="large"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
							active-text="超级管理员"
							:active-value="1"
							inactive-text="普通管理员"
							:inactive-value="2"
							@change="updateRole(scope.row)"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" align="center">
					<template #default="scope">
						<div v-if="loginAdmin == 2 && scope.row.status==1">正常</div>
						<div v-if="loginAdmin == 2 && scope.row.status==0">停用</div>
						<el-switch
							v-model="scope.row.status"
							v-if="loginAdmin==1"
							class="ml-2"
							inline-prompt
							size="large"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
							active-text="正常"
							:active-value="1"
							inactive-text="停用"
							:inactive-value="0"
							@change="updateSatus(scope.row)"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="updateTime" label="更新时间" align="center" width="200"/>
				<el-table-column fixed="right" label="操作" min-width="330" align="center">
					<template #default="{row}">
						<el-button type="info" :icon="Message" round @click="handleClick(row.id)">详情</el-button>
						<el-button type="warning" v-if="loginAdmin == 1" :icon="Edit" round
								   @click="defaultPassword(row.id)">重置密码
						</el-button>
						<el-button type="danger" v-if="loginAdmin == 1" :icon="Delete" round
								   @click="deleteById(row.id)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="adminQuery.page"
				v-model:page-size="adminQuery.limit"
				:page-sizes="[5, 10, 15, 20]"
				:size="size"
				:disabled="disabled"
				:background="background"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@change="loadData"
				style="margin-top: 20px; justify-content: flex-end"
			/>
		</el-card>
		
		<!--		添加编辑弹出框-->
		<el-dialog v-model="dialogVisible" :title="title" width="500" :lock-scroll="false">
			<el-form :model="admin">
				<el-form-item label="姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名：" :label-width="100">
					<el-input v-model="admin.name" autocomplete="off"/>
				</el-form-item>
				<el-form-item label="联系方式：" :label-width="100">
					<el-input v-model="admin.phone" autocomplete="off"/>
				</el-form-item>
				<el-form-item label="邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱：" :label-width="100">
					<el-input v-model="admin.email" autocomplete="off"/>
				</el-form-item>
				<el-form-item label="用户头像：" :label-width="100">
					<!--					后台上传接口【action="/api/upload"】 上传成功后的请求回调，拿到上传路径【:on-success="handleAvatarSuccess"】-->
					<el-upload
						class="avatar-uploader"
						action="/api/admin/upload"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:headers="headers"
					>
						<img v-if="admin.image" :src="admin.image" class="avatar"/>
						<el-icon v-else class="avatar-uploader-icon">
							<Plus/>
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="角色类型：" :label-width="100" v-if="loginAdmin==1">
					<el-select v-model="admin.role" placeholder="请选择角色类型">
						<el-option label="普通管理员" value="2"/>
						<el-option label="超级管理员" value="1"/>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="add">
						确认
					</el-button>
				</div>
			</template>
		</el-dialog>
		
		<!--		详情框-->
		<el-dialog v-model="dialogDetailsVisible" title="管理员详情" style="width: 70%;font-size:16px"
				   :lock-scroll="false">
			<el-descriptions border style="font-size:32px" :data="admin">
				<el-descriptions-item
					:rowspan="2"
					:width="160"
					label="头像"
					align="center"
					style="font-size:20px"
				>
					<el-image
						style="width: 100px; height: 100px"
						v-if="admin.image" :src="admin.image"
					/>
				</el-descriptions-item>
				<el-descriptions-item label="用户名" style="font-size: 20px" align="center">{{
						admin.name
					}}
				</el-descriptions-item>
				<el-descriptions-item label="昵称" style="font-size: 20px" align="center">{{
						admin.nickName
					}}
				</el-descriptions-item>
				<el-descriptions-item label="联系方式" align="center">{{ admin.phone }}</el-descriptions-item>
				<el-descriptions-item label="邮箱" align="center" :height="50">
					<el-tag size="large">{{ admin.email }}</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="操作" align="center" :span="3">
					<el-button type="primary" :icon="Close" round @click="dialogDetailsVisible = false">关闭</el-button>
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
	</div>

</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>